using System;
using System.Collections;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Configuration;

using Microsoft.Practices.CompositeUI;
using Microsoft.Practices.CompositeUI.SmartParts;
using Microsoft.Practices.ObjectBuilder;
using Microsoft.Practices.CompositeUI.EventBroker;

using LibrErian.Data;
using LibrErian.Model;
using LibrErian.Common;
using LibrErian.Common.Constants;
using System.Drawing;


namespace LibrErian.Modules.BasicBook
{
    public class BookViewPresenter : Presenter<IBookView>
    {
        private Book book;

        [State]
        public Book Book
        {
            set
            {
                book = value;
            }
        }

        [EventPublication("event://BooksDataUpdated", PublicationScope.Global)]
        public event EventHandler BooksDataUpdated;

        private void OnBooksDataUpdated()
        {
            if(BooksDataUpdated != null)
            {
                BooksDataUpdated(this, EventArgs.Empty);
            }
        }

        [EventSubscription("event://GenresUpdated", ThreadOption.UserInterface)]
        public void GenresUpdated(object sender, EventArgs args)
        {
            View.SetGenres(GetGenres());
        }


        public IList GetGenres()
        {
            return DataManager.GetGenres();
        }


        public IList GetFormats()
        {
            return DataManager.GetFormats();
        }


        public void Save()
        {
            DataManager.SaveOrUpdate(book);
            OnBooksDataUpdated();
        }

        public void OnImage()
        {
            SelectImage();
        }

        public override void OnViewReady()
        {
            base.OnViewReady();

            //TODO: Refactoring needed, these methods need to be called in this exact order.
            // Will cause problems in the future.
            View.SetFormats(GetFormats());
            View.SetBook(book);
            View.SetGenres(GetGenres());

            if (book.ImageId != null && book.ImageId != Guid.Empty && !string.IsNullOrEmpty(book.ImageExtension))
            {
                try
                {
                    string imageFileName = GetImageFilename(book.ImageId.ToString(), book.ImageExtension);
                    View.DisplayImage(Image.FromFile(imageFileName));
                }
                catch
                {
                    View.ShowMessage("Er is een fout opgetreden tijdens het tonen van de afbeelding");
                }
            }
        }

        public void OnRemoveAuthor(Author author)
        {
            book.Authors.Remove(author);
            View.ResetDataSource();
        }

        public void OnSelectAuthor()
        {
            ControlledWorkItem<SelectAuthorController> workItem = WorkItem.WorkItems.AddNew<ControlledWorkItem<SelectAuthorController>>();
            Author selectedAuthor = workItem.Controller.Run();
            if (selectedAuthor != null)
            {
                book.Authors.Add(selectedAuthor);
                View.ResetDataSource();
            }
        }

        public void OnManageGenre()
        {
            ControlledWorkItem<ManageGenreController> workItem = WorkItem.WorkItems.AddNew<ControlledWorkItem<ManageGenreController>>();
            workItem.Controller.Run();
        }

        public void OnCancel()
        {
            book = null;
            CloseView();
        }

        public void OnSave()
        {
            Save();
            CloseView();
        }

        private void SelectImage()
        {
            Guid newImageId;

            if (book.ImageId == null || book.ImageId == Guid.Empty)
            {
                newImageId = Guid.NewGuid();
            }
            else
            {
                newImageId = book.ImageId;
            }

            try
            {

                using (OpenFileDialog openDialog = new OpenFileDialog())
                {
                    //openDialog.Filter = "";
                    if (openDialog.ShowDialog() == DialogResult.OK)
                    {
                        FileInfo fi = new FileInfo(openDialog.FileName);

                        string destinationFileName = GetImageFilename(newImageId.ToString(), fi.Extension);

                        File.Copy(openDialog.FileName, destinationFileName, true);

                        book.ImageId = newImageId;
                        book.ImageExtension = fi.Extension;

                        View.DisplayImage(Image.FromFile(destinationFileName));
                    }
                }
            }
            catch
            {
                View.ShowMessage("Er is een fout opgetreden tijdens het selecteren van de afbeelding");
            }
        }

        private string GetImageFilename(string imageId, string extension)
        {
            string path = ConfigurationManager.AppSettings["ImageFolder"].ToString();
            if (!path.EndsWith("\\"))
            {
                path += "\\";
            }

            return string.Format("{0}{1}{2}", path, imageId, extension);
        }
    }

    public interface IBookView
    {
        void DisplayImage(Image image);
        void ShowMessage(string message);
        void SetGenres(IList genres);
        void SetBook(Book book);
        void SetFormats(IList formats);
        void ResetDataSource();
    }
}
